package beautiful.butterfly.drds.data_exchange.taskgroup.runner;


import beautiful.butterfly.drds.data_exchange.constant.State;
import beautiful.butterfly.drds.data_exchange.plugin.AbstractTaskPlugin;
import beautiful.butterfly.drds.data_exchange.plugin_collector.AbstractTaskPluginCollector;
import beautiful.butterfly.drds.data_exchange.report.Message;
import beautiful.butterfly.drds.data_exchange.report.Messages;
import beautiful.butterfly.drds.data_exchange.util.Configuration;
import lombok.NonNull;

public abstract class Task
{
    private AbstractTaskPlugin taskPlugin;


    private Message message;

    private int taskGroupId;

    private int taskId;

    public Task(AbstractTaskPlugin taskPlugin)
    {
        this.taskPlugin = taskPlugin;
    }

    public void destroy()
    {
        if (this.taskPlugin != null)
        {
            this.taskPlugin.destroy();
        }
    }


    public AbstractTaskPlugin getTaskPlugin()
    {
        return taskPlugin;
    }


    public void setConfiguration(Configuration configuration)
    {

        this.taskPlugin.setJobConfiguration(configuration);
    }

    public void setTaskPluginCollector(AbstractTaskPluginCollector abstractTaskPluginCollector)
    {
        this.taskPlugin.setAbstractTaskPluginCollector(abstractTaskPluginCollector);
    }

    private void mark(State state)
    {
        this.message.setState(state);
        if (state == State.succeeded)
        {
            // 对 stage + 1
            this.message.setLong(Messages.stage,
                    this.message.getLong(Messages.stage) + 1);
        }
    }

    public void markRun()
    {
        mark(State.running);
    }

    public void markSuccess()
    {
        mark(State.succeeded);
    }

    public void markFail(final Throwable throwable)
    {
        mark(State.failed);
        this.message.setTimestamp(System.currentTimeMillis());
        this.message.setThrowable(throwable);
    }

    public int getTaskGroupId()
    {
        return taskGroupId;
    }

    public void setTaskGroupId(int taskGroupId)
    {
        this.taskGroupId = taskGroupId;
        this.taskPlugin.setTaskGroupId(taskGroupId);
    }

    public int getTaskId()
    {
        return taskId;
    }

    public void setTaskId(int taskId)
    {
        this.taskId = taskId;
        this.taskPlugin.setTaskId(taskId);
    }

    public Message getMessage()
    {
        return message;
    }

    public void setMessage(@NonNull final Message message)
    {
        this.message = message;
    }

    public abstract void shutdown();
}
